import * as THREE from 'three'
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls'
import {GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader'

let renderer, camera, scene
let axesHelper
let dirLight
let controls
let mixer
let plane,model
let clock = new THREE.Clock()

//这里顺序很重要，加载顺序不对就要报错
initRenderer()
initScene()
initAxesHelper()
initCamera()

initLight()
initMeshes()

enableShadow()

initControls()




animate()

window.addEventListener('resize', function () {
    camera.aspect = window.innerWidth / window.innerHeight
    camera.updateProjectionMatrix()
    renderer.setSize(window.innerWidth, window.innerHeight)
})

function initRenderer() {
    renderer = new THREE.WebGLRenderer()
    renderer.setPixelRatio(window.devicePixelRatio)
    renderer.setSize(window.innerWidth, window.innerHeight)
    renderer.outputEncoding = THREE.sRGBEncoding;
    document.body.appendChild(renderer.domElement)
}

function initCamera() {
    camera = new THREE.PerspectiveCamera(60, window.innerWidth / window.innerHeight, 1, 1000)
    camera.position.set(1,2,-3)
}



function initScene() {
    scene = new THREE.Scene()
    scene.background = new THREE.Color(0x888888)
    scene.fog = new THREE.Fog(0xa0a0a0,10,50)
}

function initAxesHelper() {
    axesHelper = new THREE.AxesHelper(3)
    scene.add(axesHelper)
}




function initMeshes() {

//ground
     plane = new THREE.Mesh(
        new THREE.PlaneGeometry(100, 100),
        new THREE.MeshPhongMaterial({
            color: 0x999999
        })
        
    )
    plane.rotation.x = -Math.PI / 2
    scene.add(plane);

    const loader = new GLTFLoader();
    loader.load('models/gltf/Soldier.glb', function (gltf) {
        console.log(gltf);
        scene.add(gltf.scene);
        
        gltf.scene.traverse(function (object) {
            if (object.isMesh) {
               object.castShadow = true;
           }
       })

        const clip = gltf.animations[1]
        mixer = new THREE.AnimationMixer(gltf.scene)
        const action = mixer.clipAction(clip)
        action.play()
    });
}

function initControls() {
    controls = new OrbitControls(camera, renderer.domElement)
}

function initLight() {
    const hemisLight = new THREE.HemisphereLight(0xffffff, 0x444444)
    scene.add(hemisLight)

    dirLight = new THREE.DirectionalLight(0xffffff)
    dirLight.position.set(-3, 10, -10)
    scene.add(dirLight)
    console.log(dirLight);
}

function enableShadow() {
    renderer.shadowMap.enabled = true
    dirLight.castShadow = true
    plane.receiveShadow = true
}

function animate() {
    requestAnimationFrame(animate);

    if (mixer) {
        let delta = clock.getDelta();
        mixer.update(delta);
    }

    renderer.render(scene, camera);
}
